import tkinter as tk

# 游戏窗口尺寸
WINDOW_WIDTH = 600
WINDOW_HEIGHT = 400
# 停车位尺寸
PARKING_SIZE = 80
# 汽车尺寸
CAR_SIZE = 50
# 汽车初始位置
CAR_X = 50
CAR_Y = 50
# 停车位位置
PARKING_X = 450
PARKING_Y = 250
# 移动速度
MOVE_SPEED = 10

class ParkingGame:
    def __init__(self, root):
        self.root = root
        self.root.title("停车位游戏")
        self.canvas = tk.Canvas(root, width=WINDOW_WIDTH, height=WINDOW_HEIGHT, bg="lightgray")
        self.canvas.pack()

        # 绘制停车位
        self.parking = self.canvas.create_rectangle(PARKING_X, PARKING_Y, PARKING_X + PARKING_SIZE,
                                                    PARKING_Y + PARKING_SIZE, fill="green")
        # 绘制汽车
        self.car = self.canvas.create_rectangle(CAR_X, CAR_Y, CAR_X + CAR_SIZE, CAR_Y + CAR_SIZE, fill="blue")

        # 绑定键盘事件
        self.root.bind("<Key>", self.on_key_press)

    def on_key_press(self, event):
        key = event.keysym
        x, y, _, _ = self.canvas.coords(self.car)
        if key == "Left" and x > 0:
            self.canvas.move(self.car, -MOVE_SPEED, 0)
        elif key == "Right" and x + CAR_SIZE < WINDOW_WIDTH:
            self.canvas.move(self.car, MOVE_SPEED, 0)
        elif key == "Up" and y > 0:
            self.canvas.move(self.car, 0, -MOVE_SPEED)
        elif key == "Down" and y + CAR_SIZE < WINDOW_HEIGHT:
            self.canvas.move(self.car, 0, MOVE_SPEED)

        # 检查是否停入车位
        car_x1, car_y1, car_x2, car_y2 = self.canvas.coords(self.car)
        parking_x1, parking_y1, parking_x2, parking_y2 = self.canvas.coords(self.parking)
        if (car_x1 >= parking_x1 and car_x2 <= parking_x2 and
                car_y1 >= parking_y1 and car_y2 <= parking_y2):
            self.canvas.create_text(WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2, text="停车成功！", font=("Arial", 24))
            self.root.unbind("<Key>")  # 禁用键盘事件

if __name__ == "__main__":
    root = tk.Tk()
    game = ParkingGame(root)
    root.mainloop()